package org.sws.domain.strategy.service.rule.tree.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.sws.domain.activity.model.entity.ActivityAccountEntity;
import org.sws.domain.activity.model.entity.ActivityEntity;
import org.sws.domain.activity.repository.IActivityRepository;
import org.sws.domain.strategy.enums.RuleLogicCheckTypeVO;
import org.sws.domain.strategy.service.rule.tree.ILogicTreeNode;
import org.sws.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.sws.types.exception.AppException;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author sws
 * @Date 2025/2/25 11:16
 * @description: 奖品规则 - 低于某抽奖次数锁定规则
 */
@Slf4j
@Service("rule_lock")
public class RuleLockLogicTreeNode implements ILogicTreeNode {

    @Resource
    private IActivityRepository activityRepository;
    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId, String ruleValue, Date activityEndTime) {
        log.info("规则过滤-次数锁 userId:{} strategyId:{} awardId:{} ruleValue:{}", userId, strategyId, awardId, ruleValue);
        int raffleCount = 0;
        try {
            raffleCount = Integer.parseInt(ruleValue);
        } catch (NumberFormatException e) {
            throw new AppException("规则过滤-次数锁异常 ruleValue: " + ruleValue + " 配置不正确, 请联系运营进行修改");
        }
        int usedRaffleCount = queryRaffleCount(userId, strategyId);
        // 用户抽奖次数大于规则限定值，规则放行，正常填充奖品id
        if (usedRaffleCount >= raffleCount) {
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                    .strategyAwardData(DefaultTreeFactory.StrategyAwardData.builder().awardId(awardId).build())
                    .build();
        }

        // 用户抽奖次数小于规则限定值，规则拦截
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .strategyAwardData(DefaultTreeFactory.StrategyAwardData.builder().awardRuleValue(ruleValue).build())
                .build();
    }

    private int queryRaffleCount(String userId, Long strategyId) {
        // todo 后续可以根据枚举改写成奖品次数解锁是按照总的、月的、日的
        // 查询用户额度账户每日抽奖次数
        ActivityEntity activityEntity = activityRepository.queryRaffleActivityByStrategyId(strategyId);
        ActivityAccountEntity activityAccountEntity = activityRepository.queryActivityAccountByUserId(userId, activityEntity.getActivityId());
        if (null == activityAccountEntity) {
           return 0;
        } else {
           return activityAccountEntity.getDayCount() - activityAccountEntity.getDayCountSurplus();
        }
    }
}